/* eslint-disable @typescript-eslint/camelcase */
/* eslint-disable @typescript-eslint/no-namespace */
/* eslint-disable @typescript-eslint/no-use-before-define */
// eslint-disable-next-line spaced-comment
/// <reference types="cypress" />

import { getAuthCodeFromLocation } from './utils';

Cypress.Commands.add("keycloackLogin", (user: string) => {
  Cypress.log({name: "Login"});

  cy.fixture(`users/${user}`).then((userData) => {
  const authBaseUrl = Cypress.env("auth_base_url");
  const realm = Cypress.env("auth_realm");
  const client_id = Cypress.env("auth_client_id");

  cy.request({
      url: `${authBaseUrl}/realms/${realm}/protocol/openid-connect/auth`,
      followRedirect: false,
      qs: {
          scope: "openid",
          response_type: "code",
          approval_prompt: "auto",
          redirect_uri: Cypress.config("baseUrl"),
          client_id
      }
  })
    .then(response => {
        const html = document.createElement("html");
        html.innerHTML = response.body;

        const form = html.getElementsByTagName("form")[0];
        const url = form.action;

        return cy.request({
            method: "POST",
            url,
            followRedirect: false,
            form: true,
            body: {
                username: userData.username,
                password: userData.password
            }
        });
    })
      .then(response => {
          const code = getAuthCodeFromLocation(response.headers["location"]);

          cy.request({
              method: "post",
              url: `${authBaseUrl}/realms/${realm}/protocol/openid-connect/token`,
              body: {
                  client_id,
                  redirect_uri: Cypress.config("baseUrl"),
                  code,
                  grant_type: "authorization_code"
              },
              form: true,
              followRedirect: false
          }).its("body");
      });
  });
});

Cypress.Commands.add('keycloackLogout', () => {
  const keycloackRoot: string = Cypress.env("auth_base_url");
  const keycloackRealm: string = Cypress.env("auth_realm");
  const keycloackRedirectUri: string = Cypress.env("redirect_uri");
  return cy.request({
      url: `${keycloackRoot}/realms/${keycloackRealm}/protocol/openid-connect/logout`,
      qs: {
          redirect_uri: keycloackRedirectUri
      }
  });
});

Cypress.Commands.add('clearCache', () => {
  cy.clearCookies();
  cy.clearLocalStorage();
  cy.window().then((win) => {
    win.sessionStorage.clear()
  });
});

declare global {
  namespace Cypress {
    interface Chainable<Subject> {
      keycloackLogin(user: string): Cypress.Chainable;
      keycloackLogout(): Cypress.Chainable;
      clearCache(): Cypress.Chainable;
    }
  }
}

// Convert this to a module instead of script (allows import/export)
export {};
